import axios from 'axios'

const api = axios.create({
    baseURL: '/api/demo',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
api.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
})

// 响应拦截器
api.interceptors.response.use(response => {
    return {
        success: true,
        data: response.data?.data ?? response.data,
        status: response.status,
        fullResponse: response
    }
}, error => {
    const errorResponse = {
        success: false,
        message: '请求失败',
        status: error.response?.status || 500,
        error: error.response?.data || error.message
    }

    if (error.response?.status === 401) {
        localStorage.removeItem('token')
        window.location.reload()
    }

    return Promise.reject(errorResponse)
})

export default {
    // 用户相关
    register(userData) {
        return api.post('/reg', userData)
    },
    login(credentials) {
        return api.post('/login', credentials)
    },

    // 电影相关
    getMovies(params = {}) {
        return api.get('/getallitems', {
            params: {
                typeIndex: 3,  // movies表
                ...params
            }
        })
    },
    getMovie(id) {
        return api.get('/getsingle', {
            params: {
                typeIndex: 3,  // movies表
                id
            }
        })
    },
    addMovie(movieData) {
        return api.post('/additem', {
            typeIndex: 3,  // movies表
            ...movieData
        })
    },

    // 评论相关
    getComments(movieId) {
        return api.get('/getallitems', {
            params: {
                typeIndex: 4,  // comments表
                movieId
            }
        })
    },
    addComment(commentData) {
        return api.post('/additem', {
            typeIndex: 4,  // comments表
            ...commentData
        })
    },

    // 通用请求
    customRequest(config) {
        return api(config)
    }
}